﻿using System;
using System.Web;
using System.Web.Security;

namespace Web.Infrastructure.HttpModules
{
    public class SignalRFormsAuthenticationCleanerModule : IHttpModule
    {
        public void Init(HttpApplication application)
        {
            application.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }

        public void Dispose()
        {
        }

        private bool ShouldCleanResponse(string path)
        {
            path = path.ToLower();
            var urlsToClean = new[] { "/signalr/" };

            // Check for a Url match
            foreach (string url in urlsToClean)
            {
                bool result = path.IndexOf(url, StringComparison.OrdinalIgnoreCase) > -1;
                if (result)
                    return true;
            }

            return false;
        }

        protected void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpContext httpContext = ((HttpApplication)sender).Context;

            if (ShouldCleanResponse(httpContext.Request.Path))
            {
                // Remove Auth Cookie from response
                httpContext.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            }
        }
    }
}